package com.xyzwps.server.paimon.graphql.scalar

import graphql.GraphQLContext
import graphql.execution.CoercedVariables
import graphql.language.NullValue
import graphql.language.StringValue
import graphql.language.Value
import graphql.schema.Coercing
import graphql.schema.GraphQLScalarType
import java.util.Locale
import kotlin.time.Instant


internal object InstantCoercing : Coercing<Instant, String> {
    override fun serialize(dataFetcherResult: Any, ctx: GraphQLContext, locale: Locale): String =
        when (dataFetcherResult) {
            is Instant -> dataFetcherResult.toString()
            else -> throw IllegalArgumentException("Invalid instant")
        }

    override fun parseValue(input: Any, ctx: GraphQLContext, locale: Locale): Instant =
        when (input) {
            is Instant -> input
            is String -> Instant.parse(input)
            else -> throw IllegalArgumentException("Invalid instant")
        }

    override fun parseLiteral(input: Value<*>, vars: CoercedVariables, ctx: GraphQLContext, locale: Locale): Instant? =
        when (input) {
            is StringValue -> Instant.parse(input.value)
            is NullValue -> null
            else -> throw IllegalArgumentException("Invalid instant")
        }
}

val INSTANT_SCALAR: GraphQLScalarType = GraphQLScalarType.newScalar()
    .name("Instant")
    .description("Instant")
    .coercing(InstantCoercing)
    .build()